# -*- coding: utf-8 -*-

"""
@author: l
@Remark: 	
	
道路（路段）信息表
"""
from dvadmin.system.models import RoadsInfos
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class RoadsinfosSerializer(CustomModelSerializer):
    class Meta:
        '''
        序列化器
        '''
        model = RoadsInfos
        fields = '__all__'
        read_only_fields = ["id"]


class RoleRoadsSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """

    class Meta:
        model = RoadsInfos
        fields = ['id', 'cname']
        read_only_fields = ["id"]


class RoadsinfosViewSet(CustomModelViewSet):
    '''
    路段信息接口
    list:路段信息查询
    create:路段信息新增
    update:路段信息修改
    retrieve:路段信息单例
    destroy:路段信息删除
    multiple_delete:路段信息多删
    '''
    queryset = RoadsInfos.objects.all()
    serializer_class = RoadsinfosSerializer
    # filter_fields = ['creator_id']

    def get_user_roadinfo(self, request):
        """用于前端获取当前角色的路由"""
        user = request.user
        queryset = self.queryset
        is_admin = False
        if not user.is_superuser:
            '''
                如果角色属于管理角色，默认返回所有菜单权限
            '''
            role_admin = user.role.filter(admin=True).first()
            is_admin = role_admin is not None
        else:
            is_admin = True
        if is_admin:
            queryset = RoadsInfos.objects.all()
        else:
            Ids = user.role.values_list('road__id', flat=True)
            queryset = RoadsInfos.objects.filter(id__in=Ids)
        serializer = RoleRoadsSerializer(queryset, many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")
